<?php

namespace Simanx\Spes\Module;

use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
use Simanx\Spes\Loader\Loader;

/**
 * 模块化处理的ServiceProvider
 * @package Simanx\Spes\Module
 */
class ModuleServiceProvider extends ServiceProvider
{
    /** @var Application */
    protected $app;

    private ModuleManager $moduleManager;

    public function register()
    {
        $this->app->singleton(ModuleManager::class);
    }

    public function boot()
    {
        $this->moduleManager = $this->app->make(ModuleManager::class);
        $this->bootLoaders();
        $this->bootModulesViews();
    }

    public function bootLoaders()
    {
        $loaders = config('spes.module.loaders', []);
        foreach ($loaders as $loader => $config) {
            $config['path'] = $this->moduleManager->modulesDir($config['dir']);
            /** @var Loader $attrLoader */
            $attrLoader = app($loader, [
                'app'    => $this->app,
                'config' => $config
            ]);

            $attrLoader->load();
        }
    }

    public function bootModulesViews()
    {
        if (!config('spes.module.view')) {
            return;
        }

        foreach ($this->moduleManager->modules() as $module) {
            if ($viewPath = $module->path('view')) {
                $this->loadViewsFrom($viewPath, strtolower($module->name()));
            }

            if ($componentNameSpace = $module->getNamespace('component')) {
                $this->callAfterResolving(BladeCompiler::class, function ($blade) use ($componentNameSpace, $module) {
                    /** @var BladeCompiler $blade */
                    $blade->componentNamespace($componentNameSpace, strtolower($module->name()));
                });
            }
        }
    }
}